function wceDataFactory () {
    this.tableData = null;
    this.activeBtn = 1;
    var me = this;
    // 获取蓄水动态评价表格数据
    this.loadData = function () {
        var def = $.Deferred();
        $.getJSON("/jsite-szy-dispatch/a/szy/dispatch/ddsWeWu/listAllToMap", function (data) {
            me.tableData = data;
            def.resolve();
        });
        return def.promise();
    }
}
function getAVG(data) {
    if(data.length>0){
        var sum =data.reduce(function (p1,c) {return c+=p1})
        // var sum = data.reduce((previous, current) => current += previous);
        var avg=sum / data.length;
        return parseInt(avg);
    }else{return 0;}
}

wceDataFactory.prototype = {
    // 从tableData中获取年份数据
    getYearsFromTableData: function () {
        var data = this.tableData;
        var result = [];
        for (var year in data) {
            result.push({
                'text': year,
                'value': year
            });
        }
        return result;
    },
    getChartData: function () {
        var data = this.tableData;
        var result = {},titleYear=2017,data0_irrGwWw=[],data0_ffGwWw=[],data0_indGwWw=[],data0_pGwWw=[],data0_dGwWw=[],data0_eGwWw=[],data1_irrGwWw=[],data1_ffGwWw=[],data1_indGwWw=[],data1_pGwWw=[],data1_dGwWw=[],data1_eGwWw=[];
        for (var year in data) {
            titleYear=parseInt(year);
            for(var temp=0,l=data[year].length;temp<l;temp++){
                var tempdata=data[year][temp];
                if(tempdata.regType==0){
                    data0_irrGwWw.push(parseFloat(tempdata.irrGwWw));
                    data0_ffGwWw.push(parseFloat(tempdata.ffGwWw));
                    data0_indGwWw.push(parseFloat(tempdata.indGwWw));
                    data0_pGwWw.push(parseFloat(tempdata.pGwWw));
                    data0_dGwWw.push(parseFloat(tempdata.dGwWw));
                    data0_eGwWw.push(parseFloat(tempdata.eGwWw));
                }else if(tempdata.regType==1){
                    data1_irrGwWw.push(parseFloat(tempdata.irrGwWw));
                    data1_ffGwWw.push(parseFloat(tempdata.ffGwWw));
                    data1_indGwWw.push(parseFloat(tempdata.indGwWw));
                    data1_pGwWw.push(parseFloat(tempdata.pGwWw));
                    data1_dGwWw.push(parseFloat(tempdata.dGwWw));
                    data1_eGwWw.push(parseFloat(tempdata.eGwWw));
                }
            }
        }
        result={
            "0":{
                title: titleYear+'年行政分区用水量图',
                serieData: [{
                    type: 'pie',
                    size: '80%',
                    name: '分配比例',
                    data: [{y:getAVG(data0_irrGwWw),
                        name:'农田灌溉'},
                        {y:getAVG(data0_ffGwWw),
                            name:'林牧渔畜'},
                        {y:getAVG(data0_indGwWw),
                            name:'工业'},
                        {y:getAVG(data0_pGwWw),
                            name:'城镇公共'},
                        {y:getAVG(data0_dGwWw),
                            name:'居民生活'},
                        {y:getAVG(data0_eGwWw),
                            name:'生态环境'}]
                }]
            },
            "1":{
                title: titleYear+'年水资源分区用水量图',
                serieData: [{
                    type: 'pie',
                    size: '80%',
                    name: '分配比例',
                    data: [{y:getAVG(data1_irrGwWw),
                        name:'农田灌溉'},
                        {y:getAVG(data1_ffGwWw),
                            name:'林牧渔畜'},
                        {y:getAVG(data1_indGwWw),
                            name:'工业'},
                        {y:getAVG(data1_pGwWw),
                            name:'城镇公共'},
                        {y:getAVG(data1_dGwWw),
                            name:'居民生活'},
                        {y:getAVG(data1_eGwWw),
                            name:'生态环境'}]
                }]
            }
        }
        return result;
    },
    setTableDataByType: function () {
        var year = Ext.getCmp("wceCombo").getValue();
        var currentData = this.tableData[year];
        var type = this.activeBtn;
        var grepData = $.grep(currentData, function (obj) {
            return obj.regType == type;
        });
        Ext.data.StoreManager.lookup('wce_store1').setData(grepData);
    }
}

var wceData;

Ext.define('Admin.view.evaluation.wce.WceController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.wceController',
    views: ['Admin.view.evaluation.wce.Wce'],
    buildChart: function (dom) {
        var chartId = dom.el.id + "-body";
        _wceChart.init(chartId);
    },
    initData: function (_this, opt) {
        var myMask = new Ext.LoadMask(Ext.ComponentQuery.query('wce')[0], { msg: "正在加载..." });
        myMask.show();
        var me = this;
        wceData = new wceDataFactory();
        $.when(wceData.loadData())
            .done(function () {
                _wceChart.dataMap=wceData.getChartData();
                // 设置年份数据
                var yearData = wceData.getYearsFromTableData();
                var firstSelect = yearData.length > 0 ? yearData[0].value : '';
                var year_store = Ext.create('Ext.data.Store', {
                    fields: ['text', 'value'],
                    data: yearData
                });
                Ext.create('Ext.form.ComboBox', {
                    renderTo: 'wceComboWrapper',
                    id: 'wceCombo',
                    labelWidth: 35,
                    emptyText: '请选择',
                    fieldLabel: "年份",
                    valueField: 'value',
                    displayField: 'text',
                    value: firstSelect,
                    editable: false,
                    store: year_store,
                    listeners: {
                        'change': me.changeYear
                    }
                });
                Ext.getCmp('wceBtn1').fireEvent('click');
                myMask.hide();
            });
    },
    changeYear: function (_this, newVal, oldVal, opt) {
        wceData.setTableDataByType();
    },
    switchAdminRegion: function () {
        const type = 0;
        wceData.activeBtn = type;
        wceData.setTableDataByType();
        _wceChart.chartType = "0";
        if (_wceChart.chartid !== null) {
            _wceChart.change();
        }
    },
    switchWaterRegion: function () {
        const type = 1;
        wceData.activeBtn = type;
        wceData.setTableDataByType();
        _wceChart.chartType = "1";
        if (_wceChart.chartid !== null) {
            _wceChart.change();
        }
    },
})

function wceChart(id) {
    this.dataMap = {
        "0":{
            title: '2017年行政分区用水量图',
            serieData: [{
                type: 'pie',
                size: '80%',
                name: '占比',
                data: [{y:2,
                    name:'农田灌溉'},
                    {y:3,
                        name:'林牧渔畜'},
                    {y:4,
                        name:'工业'},
                    {y:4,
                        name:'城镇公共'},
                    {y:5,
                        name:'居民生活'},
                    {y:6,
                        name:'生态环境'}]
            }]
        },
        "1":{
            title: '2017年水资源分区用水量图',
            serieData: [{
                type: 'pie',
                size: '80%',
                name: '占比',
                data: [{y:2,
                    name:'农田灌溉'},
                    {y:3,
                        name:'林牧渔畜'},
                    {y:4,
                        name:'工业'},
                    {y:4,
                        name:'城镇公共'},
                    {y:5,
                        name:'居民生活'},
                    {y:6,
                        name:'生态环境'}]
            }]
        }
    };
    this.chartid = null;
    this.chartType = "0";
}

wceChart.prototype = {
    init: function (id) {
        var data = this.dataMap[this.chartType];
        this.chartid = id;
        $('#' + id).highcharts(this.getOption(data));
    },
    change: function () {
        var data = this.dataMap[this.chartType];
        $('#' + this.chartid).highcharts(this.getOption(data));
    },
    getOption: function (data) {
        return {
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            title: {
                text: data.title
            },
            tooltip: {
                headerFormat: '{series.name}<br>',
                pointFormat: '{point.name}: <b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                        style: {
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                        }
                    },
                    showInLegend: true
                }
            },
            series: data.serieData,
            credits: { enabled: false }
        };
    }
}

var _wceChart = new wceChart();
